package onetoonemapping;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;

public class Program {

	public static void main(String[] args) {
		System.out.println("Working with Stocks");
		
		SessionFactory sessions=new AnnotationConfiguration().configure("one_to_one_Stock_hibernate.cfg.xml").buildSessionFactory();
		
		Session session=sessions.openSession();
		session.getTransaction().begin();
		
		//////////////////////////////////////get Stock and its child stockDetail
		Stock currentStock=(Stock)session.createQuery("from Stock where id=1").list().get(0);
		
		
		// T
		///////////////////////!!!!!!!!!!!!!!!!Save new stock  , to save some object we need  session.getTransaction().begin();  
		//// and session.getTransaction().commit();
		
		Stock stock=new Stock();
		stock.setName("temporary");
		
		StockDetail detail=new StockDetail();
		//detail.setId(stock.getId()); // we dont need to set , because we set the same id's in annotation @GenericGenerator(name="gen", strategy="foreign"..... 
		detail.setAddress(".");
		detail.setComment(".");
		detail.setStock1(stock);
		stock.setStockDetail(detail);
		session.save(stock);
		////////////////////////////
		
		///////////////////////////////////////get stockDetail , and get it parent Stock
/*		StockDetail currentStockDetail=(StockDetail)session.createQuery("from StockDetail where id=1").uniqueResult();
		System.out.println(currentStockDetail.getAddress());
		System.out.println(currentStockDetail.getStock1().getId()+" "+currentStockDetail.getStock1().getName());*/
		
		
		
		 
		
		// session.load and session.get - are almost similar , but if we use load method and pass non existing id we will have EXCEPTION
		// if we use get method and pass non existing id , the get method return null 
	/*	Stock first=(Stock) session.load(Stock.class, 3);
		System.out.println(first.getName());*/
		
		
		session.getTransaction().commit();
		session.close();
	}
}
